import sys,os
from subprocess import *

if len(sys.argv)<2:
    print 'Usage: python updateBCS.py mysql.log'
    exit(1)

def getType(name):
    p=Popen(['mysql','-uroot','-N','hg19','-e','select type from trackDb where tableName=\''+name+'\''],stdout=PIPE)
    type=p.stdout.readlines()
    if len(type)<1:
    	return ''
    return type[0].strip()

fi=open(sys.argv[1],'r')
foT=open('type_update.lst','w')
outfile='id_update.lst'
tablefile='tableData'
for line in fi:
    if 'MYD' not in line:
    	continue
    line=line.strip()
    temp=line.split('hg19/')
    name=temp[1].split('.')[0]
    type=getType(name)
    if len(type)<1:
    	continue
    if 'bigWig' in type:
    	p=Popen(['mysql','-uroot','-N','hg19','-e','select * from '+name],stdout=PIPE)
    	fpath=p.stdout.readline().strip().replace('/gbdb','/home/ruijie/gbdb')
	if len(fpath)<1:
	    continue
    	bcs='py ../gis-basic-storage/console/bcs.py build bigWig -i '+fpath+' -F bigWig --importmode=softlink --tags=\'assembly=hg19;UCSC_name='+name+'\' --queryop=\'max,access\' >>'+outfile+' 2>&1'
    elif 'narrowPeak' in type:
	bcs='py ../gis-basic-storage/console/bcs.py load mongodb_table -F encodeNarrowPeak:encodeNarrowPeak --tags=\'assembly=hg19;UCSC_name='+name+'\' -i ./narrowPeak/'+name+'.narrowPeak >>'+outfile+' 2>&1'
    elif 'bed' in type:
    	n=type.split(' ')[1]
	bcs='py ../gis-basic-storage/console/bcs.py load mongodb_table -F bed'+n+':bed'+n+' --tags=\'assembly=hg19;UCSC_name='+name+'\' -i ./bed/'+name+'.bed >>'+outfile+' 2>&1'
    elif 'broadPeak' in type:
	bcs='py ../gis-basic-storage/console/bcs.py load mongodb_table -F encodeBroadPeak:encodeBroadPeak --tags=\'assembly=hg19;UCSC_name='+line+'\' -i ./broadPeak/'+line+'.broadPeak'
    else:
    	continue
    foT.write(type+'\n')
    print bcs
#    os.system(bcs)
fi.close()
foT.close()
